extends Node

# 【内嵌】进入树时
func _enter_tree() -> void:
	print('MAIN==========_enter_tree=======')
	
# 【内嵌】离开树时
func _exit_tree() -> void:
	pass
	
# 【内嵌】初始化时
func _init() -> void:
	pass
	
# 创建一个玩家类
var player = Player.new()

var logo :MovingLogo
var save_btn :SaveButton
var load_btn :LoadButton

# 【内嵌】场景准备好后
func _ready() -> void:
	print('MAIN==========_ready============')
	
	# 从父节点获取子节点，并操作节点
	var label = self.get_node("Label")
	label.text = "Push Start"
	print(label)
	
	# 从上到下的访问优于从下向上的访问，这样在子节点进行独立测试时会因为与父节点的耦合而无法进行
	# 也就是子节点只要发出信号即可，而上层节点通过动态连接到信号进行处理
	# 这里值得注意的一点，当前父节点是最后初始化的，因此如果在子类的_ready中发送消息，父类是无法收到的，因为还没有初始化完成
	logo = self.get_node("Sprite2D_Logo")
	logo.logo_node_ready.connect(_node_ready.bind("this is a message"))
	#logo.connect("logo_node_ready", _node_ready, 0)
	
	player.player_name = "Zippy"
	print(player.player_name + "=====Score:" + String.num(player.high_score.value))
	
	save_btn = self.get_node("SaveButton")
	save_btn.save_data.connect(_save_data)
	
	load_btn = self.get_node("LoadButton")
	load_btn.load_data.connect(_load_data)

# 【内嵌】
func _process(delta: float):
	self.input_process(delta)
	return delta

# 【内嵌】
func _physics_process(delta: float) -> void:
	pass
	
func add(a, b:int=0) -> int:
	print('compute a + b = ??')
	return a+b
	
func _node_ready(msg:String):
	print('get single==========' + msg)

const FILE_NAME = "user://file_name.res"

func _save_data():
	print('：：：：开始保存数据==========')
	var result = ResourceSaver.save(player, FILE_NAME)
	assert(result == OK)
	pass
	
func _load_data():
	print('：：：：开始加载数据==========')
	if ResourceLoader.exists(FILE_NAME):
		var load_player = ResourceLoader.load(FILE_NAME)
		if load_player is Player: # Check that the data is valid
			self.player = load_player
			print('==Get Player: %s' % self.player.player_name)

func _on_sprite_2d_logo_logo_node_ready() -> void:
	print('get single++++++++++')

func input_process(delta: float):
	if (Input.is_action_just_pressed("ui_accept")):
		# Print to Output window
		print("Key down")
	if (Input.is_action_just_released("ui_accept")):
		print("Key up")
	
	if (Input.is_action_pressed("ui_up")):
		self.logo.logo_move_up.emit("moveup", 1)
	if (Input.is_action_pressed("ui_down")):
		self.logo.logo_move_down.emit()
	if (Input.is_action_pressed("ui_left")):
		self.logo.logo_move_left.emit()
	if (Input.is_action_pressed("ui_right")):
		self.logo.logo_move_right.emit()
	
	if (Input.is_key_pressed(KEY_F)):
		var fps = 1.0 / delta
		print("FPS: %d" % fps)
	if (Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT)):
		print("Left mouse button pressed!")
	if (Input.get_mouse_button_mask() == 0x03):
		print("Left and right mouse buttons pressed!")
	if (Input.is_key_pressed(KEY_ESCAPE)):
		get_tree().quit()
